import json
import subprocess

import requests

PORT = "8080"
IP = "192.168.108.199"

VMID = "7702970b-aa4a-44fa-88b0-e450886265e3"
USERNAME = "pangbaochuan"
PASSWORD = "admin__1"
ENC_PASSWORD = "ZLlAS9IPFJc="

# VMID = "b46e13c2-1232-428a-9bc1-46de26db3e94"
# USERNAME = "wangsong"
# PASSWORD = "123456"
# ENC_PASSWORD = "lTXhvSj4mzk="



########################## ｏｐｅｎvm -top
url = 'http://%s:%s/api/vms/%s/operate' % (IP, PORT, VMID)
payload = {
    "login": USERNAME,
    "password": ENC_PASSWORD,
    "operateType": "start"
}
headers = {'content-type': 'application/json'}
requests.post(url, data=json.dumps(payload), headers=headers, timeout=20)
########################## ｏｐｅｎvm -end


########################## ticket -top
URL = "http://%s:%s/api/vms/%s/ticket" % (IP, PORT, VMID)
DATE = {
    "displayName": "xxxx",
    "inDomain": "false",
    "login": USERNAME,
    "password": ENC_PASSWORD
}
headers = {'content-type': 'application/json'}
recv = requests.post(URL, data=json.dumps(DATE), headers=headers, timeout=30)
TICKET = json.loads(recv.text).get("result").get("result").get("value")
########################## ticket -end


########################## host addr:port -top
URL2 = "http://%s:%s/api/vitualMachine/vms/%s" % (IP, PORT, VMID)
recv_vminfo = requests.get(URL2)
HOST_URL = \
    json.loads(recv_vminfo.text).get("result").get("result").get("display").get("certificate").get("subject").split(
        "CN=")[
        1]
VM_PORT = json.loads(recv_vminfo.text).get("result").get("result").get("display").get("securePort")
########################## host addr:port -end


########################## CERT -top
URL3 = "http://%s:%s/api/downloadcert/%s" % (IP, PORT, VMID)
CERT_INFO = requests.get(URL3)
tmp_command_str1 = "echo \'%s\' > /tmp/spice.pem" % (CERT_INFO.text)
subprocess.getstatusoutput(tmp_command_str1)
SPICE_URL = "spice://%s/?tls-port=%s&password=%s" % (HOST_URL, VM_PORT, TICKET)
CERT_URL = "--spice-ca-file=/tmp/spice.pem"
########################## CERT -end


args = []
args.append("window")
args.append(SPICE_URL)
args.append(CERT_URL)

subprocess.Popen(args)